package com.paw.response.config;

import cn.hutool.json.JSONUtil;
import com.paw.response.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;



@Slf4j
@ControllerAdvice(basePackages = "com.paw.response")
public class ApiResponseBodyAdvice implements ResponseBodyAdvice {



  @Override
  public boolean supports (MethodParameter methodParameter, Class converterType) {
    boolean supported = methodParameter.getMethod().getReturnType().equals(Result.class);
    return true;
  }

  @Override
  public Object beforeBodyWrite (Object body, MethodParameter methodParameter, MediaType selectedContentType, Class selectedConverterType,
      ServerHttpRequest request,
      ServerHttpResponse response) {
    String path = request.getURI().getPath();
    String klassMethod = methodParameter.getMethod().getDeclaringClass().getName() + "#" + methodParameter.getMethod().getName();
    log.info("request uri: {} method: {}", path, klassMethod);

    if(body instanceof String){
      Result result = new Result(200,"success",body);
      return JSONUtil.toJsonStr(result);
    }
    if (!(body instanceof Result)) {
      return body;
    }
    Result result = (Result) body;
    AntPathMatcher pathMatcher = new AntPathMatcher();
    boolean matched = pathMatcher.match("/api/newUri/**", path);
    log.info("path match {} {}", path, matched);
    if (matched) {
      // 重写返回码 result.setCode(newCode);
    }
    // 生成新的规范化转码 newCode
    // result.setCode(newCode);

    return result;
  }




}
